import React, { Component } from "react";
import { connect } from "dva";
import store from "store";
import { withRouter } from "dva/router";
import {
  Form,
  Input,
  Button,
  Icon,
  Modal,
  Alert,
  Card,
  List,
  Avatar,
  Select,
  message
} from "antd";

import "./less/depart.less";
// import * as ajax from "../../../services/api";
import {
  enterpriseInsComInsSaveBookScheme,
  enterpriseInsComInsGetBlbProList //获取产品列表
} from "../../../services/api";

// const { MenuItemGroup } = Menu;
const FormItem = Form.Item;
const { Option } = Select;
@connect(state => ({
  profile: state.profile,
  companyInfo: state.global.companyInfo
}))
@Form.create()
@withRouter

/**
 * 部门管理组件
 */
export default class GetPlanBook extends Component {
  constructor(props, context) {
    super(props, context);
    console.log(props, "props");
    this.state = {
      insurancetipsvisible: this.props.insurancetipsvisible, //提示模板
      policyHolder: this.props.companyInfo.comName, //投保人
      contactper: "", //联系人
      contactPhone: "", //联系方式
      comPerNum: "", //企业人数
      guaranteeAmountLow: "", //保障金额下限
      insAmountUp: "", //保费上限
      accessbookvisible: false, //获取方案书
      disabled: true,
      productvisible: false, //选择产品
      productlistdata: [],
      isIns: this.props.isIns || ""
      // comName:"",//企业名称
    };
  }

  componentDidMount() {}

  componentWillReceiveProps(nextprops) {
    if (
      nextprops.insurancetipsvisible &&
      nextprops.insurancetipsvisible !== this.state.insurancetipsvisible
    ) {
      this.setState({ insurancetipsvisible: nextprops.insurancetipsvisible });
    }
    if (
      nextprops.accessbookvisible &&
      nextprops.accessbookvisible !== this.state.accessbookvisible
    ) {
      this.setState({ accessbookvisible: nextprops.accessbookvisible });
    }

    if (nextprops.isIns !== this.state.isIns) {
      this.setState({ isIns: nextprops.isIns });
    }
  }

  handlenextpeopleOk = e => {
    //获取方案书表单提交
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.getProductList();
        const {
          contactper = "",
          contactPhone = "",
          comPerNum = "",
          guaranteeAmountLow = "",
          insAmountUp = "",
          proCode = ""
        } = values;
        const obj = {
          contactper,
          contactPhone,
          comPerNum,
          guaranteeAmountLow,
          insAmountUp,
          proCode
        };

        this.setState(obj);
        this.props.okorcancel("accessbookvisible", false);
        this.setState({
          accessbookvisible: false,
          productvisible: true
        });
      }
    });
  };

  // 选择产品
  chooseProductClick = (item, index) => {
    const productlistdata = [...this.state.productlistdata].map((val, key) => {
      if (key !== index) {
        val.isCheck = false;
      }
      if (key === index) {
        val.isCheck = true;
      }
      return val;
    });
    this.setState({ productlistdata });
    console.log("选择的产品", productlistdata);
  };

  handlereducepeopleCancel = () => {
    this.props.okorcancel("accessbookvisible", false);

    this.setState({
      accessbookvisible: false,
      insurancetipsvisible: false
    });
  };

  handleproductxCancel = e => {
    console.log(e);
    this.props.okorcancel("productvisible", false);

    this.setState({
      productvisible: false
    });
  };
  handleproductCancel = () => {
    this.props.okorcancel("productvisible", false);

    this.setState({
      productvisible: false,
      accessbookvisible: true
    });
  };

  handlesurancetipxCancel = e => {
    console.log(e);
    this.props.okorcancel("insurancetipsvisible", false);

    this.setState({
      insurancetipsvisible: false
      // insurancetipvisible:true,
    });
  };

  handlesurancetipCancel = e => {
    console.log(e);
    this.props.okorcancel("insurancetipsvisible", false);

    this.setState({
      // insurancetipvisible: false,
      insurancetipsvisible: false
    });
    this.props.history.push(
      // 跳转到1-4-4
      "/enterprise/company"
    );
  };

  handlesuranceOk = e => {
    console.log(e);
    this.props.okorcancel("insurancetipsvisible", false);
    this.setState({
      insurancetipsvisible: false,
      accessbookvisible: true
    });
  };

  // 获取产品列表
  getProductList = () => {
    enterpriseInsComInsGetBlbProList({}).then(data => {
      const productlistdata = data.data.map(val => {
        return { ...val, ...{ isCheck: false } };
      });
      this.setState({ productlistdata });
      console.log("获取产品列表", data);
    });
  };

  handleproductOk = () => {
    const item = this.state.productlistdata.find(val => val.isCheck === true);
    if (!item) {
      message.error("请选择产品");
      return;
    }
    const {
      contactper,
      contactPhone,
      comPerNum,
      guaranteeAmountLow,
      insAmountUp
    } = this.state;

    enterpriseInsComInsSaveBookScheme({
      contactper,
      contactPhone,
      comPerNum,
      guaranteeAmountLow,
      insAmountUp,
      proCode: item.proCode,
      insBootName: `${item.nsBootName}方案书`
    }).then(
      res => {
        console.log("成功信息-方案书values", res);
        this.setState({ productvisible: false });
        this.props.history.replace("/insurancemanagement/insurancePlan");
      },
      err1 => {
        console.log("错误信息-err", err1);
      }
    );
  };

  // 温馨提示马上查看
  rightCheckClick = () => {
    this.props.history.push(`/insurancemanagement/enterpriseinsurance`);
  };

  render() {
    //获取方案书
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 7 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 15 },
        sm: { span: 15 },
        md: { span: 15 }
      }
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 15, offset: 7 },
        sm: { span: 15, offset: 7 }
      }
    };

    return (
      <div className="getPlanBook">
        {/* 温馨提示 */}
        <Modal
          className="surancetip"
          title="温馨提示"
          visible={this.state.insurancetipsvisible}
          onOk={this.handlesuranceOk}
          onCancel={this.handlesurancetipxCancel}
          footer={false}
        >
          <div>
            {this.state.isIns === "0" && (
              <Alert
                message="很遗憾，贵公司未购买保险产品。请依照政策要求购买符合条件的保险产品。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === "1" && (
              <Alert
                message="很遗憾，贵司所投保人数不符合政策要求。请保证所有保安都已投保。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === "2" && (
              <Alert
                message="很遗憾，贵司所购买的保险保额不符合政策要求。请保证所有保安的总保障额度符合要求。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === "3" && (
              <Alert
                message="很遗憾，贵司所购买的保险保额和投保人数不符合政策要求。请依照政策要求购买。"
                type="warning"
                showIcon
              />
            )}
          </div>
          {this.state.isIns === "9" && (
            <p>
              恭喜贵司，已符合**地区保安从业单位应为保安员投保的相关政策要求，您还可继续投保为员工提高保障额度
            </p>
          )}
          {this.state.isIns !== "9" && (
            <p>
              根据陕西保安监管部门通知规定：保安员意外伤害保险投保保额不低于陕西省平均人身损害赔偿标准（约37万元），若企业未按照通知的规定投保保安员意外伤害保险并通过保安服务监管信息系统将投保情况实时向公安机关报备的，年报不予通过。
            </p>
          )}
          {this.state.isIns === "9" && (
            <div className="intbtn">
              <Button key="back" onClick={this.handlesurancetipCancel}>
                已购买保险
              </Button>
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "1" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "2" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "3" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "0" && (
            <div className="intbtn">
              <Button key="back" onClick={this.rightCheckClick}>
                马上查看
              </Button>
              <Button
                key="submit"
                type="primary"
                onClick={this.handlereducepeopleCancel}
              >
                以后再说
              </Button>
            </div>
          )}
        </Modal>

        {/* 获取方案书 */}
        <Modal
          className="accessbook"
          title="获取方案书"
          visible={this.state.accessbookvisible}
          onOk={this.handlenextpeopleOk}
          onCancel={this.handlereducepeopleCancel}
          footer={null}
        >
          <div style={{ paddingBottom: 16 }}>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
              <FormItem {...formItemLayout} label="投保人">
                {getFieldDecorator("policyHolder", {
                  // {}
                  initialValue: this.state.policyHolder,
                  rules: [{ message: "请填写" }]
                })(<Input disabled={this.state.disabled} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="联系人">
                {getFieldDecorator("contactper", {
                  initialValue: this.state.contactper,
                  rules: [{ required: true, message: "限制长度20位", max: 20 }]
                })(<Input placeholder="请填写" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="联系方式">
                {getFieldDecorator("contactPhone", {
                  initialValue: this.state.contactPhone,
                  rules: [
                    { required: true, message: "请输入" },
                    { validator: this.checkPhone }
                  ]
                })(<Input placeholder="请填写" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="企业人数">
                {getFieldDecorator("comPerNum", {
                  initialValue: this.state.comPerNum,
                  rules: [
                    { message: "限制长度7位数字", max: 7 },
                    { validator: this.checkpeoplenum }
                  ]
                })(<Input placeholder="请输入" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="保障金额不低于">
                {getFieldDecorator("guaranteeAmountLow", {
                  initialValue: this.state.guaranteeAmountLow,
                  rules: [{ required: true, message: "请选择" }]
                })(
                  <Select placeholder="请选择">
                    <Option key="0" value="20">
                      20万
                    </Option>
                    <Option key="1" value="40">
                      40万
                    </Option>
                    <Option key="2" value="60">
                      60万
                    </Option>
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="保费不超过">
                {getFieldDecorator("insAmountUp", {
                  initialValue: this.state.insAmountUp,
                  rules: [{ required: true, message: "请选择" }]
                })(
                  <Select placeholder="请选择">
                    <Option key="0" value="600">
                      600元（不含600元）
                    </Option>
                    <Option key="1" value="400">
                      400元（不含400元）
                    </Option>
                    <Option key="2" value="200">
                      200元（不含200元）
                    </Option>
                  </Select>
                )}
              </FormItem>
              <FormItem {...submitFormLayout} style={{ marginBottom: 0 }}>
                <Button
                  loading={submitting}
                  onClick={this.handlereducepeopleCancel}
                >
                  晚点再看
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: 8 }}
                  htmlType="submit"
                  onClick={this.handlenextpeopleOk}
                >
                  下一步
                </Button>
              </FormItem>
            </Form>
          </div>
        </Modal>
        {/* 选择产品 */}
        <Modal
          className="chooseproductlist"
          title="选择产品"
          visible={this.state.productvisible}
          onOk={this.handleproductOk}
          onCancel={this.handleproductxCancel}
          footer={[
            <Button key="back" onClick={this.handleproductCancel}>
              上一步
            </Button>,
            <Button key="submit" type="primary" onClick={this.handleproductOk}>
              保存
            </Button>
          ]}
        >
          <div className="chooseproduct">
            <Alert message="请选择您感兴趣的产品！" type="info" showIcon />
            <Card>
              <List
                itemLayout="horizontal"
                dataSource={this.state.productlistdata}
                renderItem={(item, index) => (
                  <List.Item
                    onClick={this.chooseProductClick.bind(this, item, index)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar src={item.proImgPath} />}
                      title={<a>{item.insName}</a>}
                      description={
                        <div style={{ cursor: "pointer" }}>
                          <div>{item.proIntro}</div>
                          <div className="premium">
                            保费：<span className="guaranteebig">
                              {item.insFee}
                            </span>
                            <span
                              className="guaranteesm"
                              style={{ marginRight: 20 }}
                            >
                              元/人
                            </span>
                            保障金额：<span className="guaranteebig">60</span>
                            <span className="guaranteebigsm">万</span>
                            {item.isCheck && (
                              <Icon
                                type="check-circle-o"
                                className="productselect"
                              />
                            )}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </div>
        </Modal>
      </div>
    );
  }
}
